<template>
  <div class="container">
    <div class="app-container">
      <!-- 左上角 添加角色按钮 -->
      <div class="btn-container"><el-button type="primary" size="mini" @click="showDialog=true">添加角色</el-button></div>
      <!-- 在中间 展示角色列表 -->
      <el-table align="center" :data="tableList">
        <el-table-column prop="name" width="200px" label="角色" align="center">
          <template v-slot="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
            <!-- <el-input v-if="row.isEdit" size="mini" /> -->
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" width="200px" label="启用" align="center">
          <template v-slot="{row}">
            <!-- <span v-if="row.isEdit">按钮</span> -->
            <el-switch v-if="row.isEdit" v-model="row.editRow.state" :active-value="1" :inactive-value="0" />
            <span v-else>{{ row.state === 1 ? '启用✅' :row.state === 0 ? '未启用❌' : '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" align="center">
          <template v-slot="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" size="mini" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <!-- 放置操作按钮 -->
          <template v-slot="{ row }">
            <template v-if="row.isEdit">
              <el-button plain size="mini" type="primary" @click="btnEditOK">确定</el-button>
              <el-button plain size="mini" type="danger" @click="row.isEdit = false">取消</el-button>
            </template>
            <template v-else>
              <el-button plain size="mini" type="success">分配权限</el-button>
              <el-button plain size="mini" type="primary" @click="editClick(row)">编辑</el-button>
              <!-- <el-button plain size="mini" type="danger" @click="delClick">删除</el-button> -->
              <el-popconfirm title="您确定删除该角色吗？" @onConfirm="delConfirmClick(row)">
                <el-button slot="reference" plain size="mini" type="danger">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 右下角 加一个分页器 -->
      <el-row type="flex" justify="end" style="height:60px" align="middle">
        <el-pagination
          background
          :current-page="pageParams.page"
          :page-size="pageParams.pagesize"
          :total="pageParams.total"
          layout="prev,pager,next"
          @current-change="handleCurrentChange"
        />
      </el-row>
    </div>
    <!-- 放置弹层 -->
    <el-dialog title="新增角色" :visible.sync="showDialog" width="500px" @close="close">
      <!-- 表单 -->
      <el-form ref="roleForm" label-width="120px" :rules="rules" :model="roleForm">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" size="mini" style="width:300px" />
        </el-form-item>
        <el-form-item label="启用" prop="state">
          <!-- <el-switch v-if="row.isEdit" v-model="roleForm.state" :active-value="1" :inactive-value="0" /> -->
          <el-switch v-model="roleForm.state" :active-value="1" :inactive-value="0" />

        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <!-- <el-input v-if="row.isEdit" v-model="roleForm.description" type="textarea" rows="3" size="mini" style="width:300px" /> -->
          <el-input v-model="roleForm.description" type="textarea" rows="3" size="mini" style="width:300px" />

        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini" @click="BtnOK">确认</el-button>
              <el-button size="mini" @click="close">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { addRoleList, delRoleList, getRoleList, updateRoleList } from '@/api/role'
export default {
  name: 'Role',
  data() {
    return {
      tableList: [],
      // 多个不同变量 完成相同事 写到对象中
      // 也是为了方便接口使用
      pageParams: {
        page: 1, // 当前页面
        pagesize: 5, // 每页条数
        total: 0// 总条数
      },
      showDialog: false,
      description: '', // 角色描述
      state: 1, // 角色状态 默认启用 1
      roleForm: {
        name: '',
        description: '',
        state: 1
      },
      rules: {
        name: [{ required: true, message: '不为空', trigger: 'blur' }],
        description: [{ required: true, message: '不为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    // 获取角色列表数据
    this.getRoles()
  },
  methods: {
    // 获取角色列表
    async getRoles() {
      // 调用获取接口列表方法
      const { total, rows } = await getRoleList(this.pageParams)
      // console.log(rows)
      this.tableList = rows
      this.pageParams.total = total
      // 行内编辑准备 给每一行的数据定位编辑标记 状态
      // 定义行内数据编辑的标记
      this.tableList.forEach(item => {
      // item.isEdit = false
      // 响应式 针对每个数据定义标记
      // this.$set(目标对象，属性名称，初始值)
      // 等价于 Vue.set（目标对象，属性名称，属性值）
      // 向响应式对象中添加一个属性 并确保这个新属性也是响应式的 且触发试图更新
        this.$set(item, 'isEdit', false)
        // 初始化定义时缓存数据
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
    },
    // 分页器改变
    handleCurrentChange(currentPage) {
      // console.log(currentPage)
      // 更新页码
      this.pageParams.page = currentPage
      // 获取角色列表数据
      this.getRoles()
    },
    // 确认新增按钮
    BtnOK() {
      // 表单整体校验
      this.$refs.roleForm.validate(async isOK => {
        if (isOK) {
          await addRoleList(this.roleForm)
          // 新增角色成功
          // 友好提示用户
          this.$message.success('新增角色成功')
          // 重新加载角色列表
          this.getRoles()
          // 重制表单关闭碳层
          this.close()
        }
      })
    },
    // 关闭按钮
    close() {
      // 关闭
      this.$refs.roleForm.resetFields()
      this.showDialog = false
    },
    // 确认添加按钮
    editClick(row) {
      console.log(row.state)
      row.isEdit = true
      console.log(row.isEdit)
      // 点击编辑更新缓存
      row.editRow.name = row.name
      row.editRow.description = row.description
      row.editRow.state = row.state
    },
    // 删除角色
    async delConfirmClick(row) {
      this.$message.success('删除成功')
      await delRoleList(row.id)
      if (this.tableList.length === 1) {
        this.pageParams.page--
      }
      this.getRoles()
    },
    // 确认修改
    async btnEditOK(row) {
      if (row.editRow.name && row.editRow.description) {
        await updateRoleList({ ...row.editRow, id: row.id })
        this.message.success('更新成功')
        // 爆红 解决办法1 快速修复
        // this.message.warning('不能为空')
        // 解决办法2
        Object.assign(row, {
          // name:row.editRow.name
          // state:row.editRow.state
          // description:row.editRow.description
          // 简写为 ...row.editRow
          ...row.editRow,
          isEdit: false

        })
      } else {
        this.message.warning('不能为空')
      }
    }
  }
}
</script>
<style scoped lang="scss">
.btn-container{
  padding: 10px;
}
</style>
